'use strict';
const BaseController = require('./base');
const serviceName = 'category';
// 继承baseController 并且指定serviceName
class RouterController extends BaseController {
  constructor(ctx) {
    super(ctx, serviceName);
  }
  getListQuery(query) {
    if (query.type) {
      return {
        type: query.type
      }
    }
    return  {}
  }
  async tree() {
    const { ctx } = this;
    let where = {}
    if (ctx.query.type) {
      where.type = ctx.query.type
    }
    // Get all categories
    const categories = await ctx.model.Category.findAll({
      order: [['sort', 'ASC'], ['id', 'DESC']],
      where: {
        ...where
      }
    });

    // Build tree structure
    const tree = [];
    const map = {};

    categories.forEach(item => {
      map[item.id] = { ...item.dataValues, children: [] };
    });

    categories.forEach(item => {
      const id = item.id;
      const parentId = item.parent_id;

      if (parentId === 0) {
        tree.push(map[id]);
      } else {
        if (map[parentId]) {
          map[parentId].children.push(map[id]);
        }
      }
    });
    this.ctx.success(tree)
  }
}
module.exports = RouterController;
